
package com.v1.video.activity;

import java.io.File;
import java.io.FileOutputStream;
import java.util.ArrayList;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.media.AudioManager;
import android.media.MediaMetadataRetriever;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnBufferingUpdateListener;
import android.media.MediaPlayer.OnCompletionListener;
import android.media.MediaPlayer.OnErrorListener;
import android.media.MediaPlayer.OnPreparedListener;
import android.media.MediaPlayer.OnSeekCompleteListener;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.view.Display;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.TextView;

import com.iss.app.IssActivity;
import com.iss.view.common.ToastAlone;
import com.v1.video.AppContext;
import com.v1.video.R;
import com.v1.video.domain.OptionInfo;
import com.v1.video.domain.VideoBaseInfo;
import com.v1.video.util.Logger;
import com.v1.video.util.Utils;
import com.v1.video.view.CustomVideoView;
import com.v1.video.view.CustomVideoView.SizeChangeLinstener;

/**
 * 传递两个参数
 * <br/>
 *  1. 播放列表位置
     int positionInVideoList;  默认0<br/>
    2.视频列表
     ArrayList&lt;VideoBaseInfo> videoList;<br/>
    3.是否显示 上一条 下一条，返回首页按钮
    boolean showOption； 。。默认是false，不显示，零流量需要传递<br/>
    4.当前视频的播放位置（进度）
    int position； 。。默认0
 *
 */
public class VideoPlayerActivity extends IssActivity implements OnClickListener {
    protected static final String TAG = "VideoPlayerActivity";

    /** 手机或模拟器的屏幕宽 */
    private static int screenWidth = 0;

    /** 手机或模拟器的屏幕高 */
    private static int screenHeight = 0;

    /** 默认屏幕 */
    private final static int SCREEN_DEFAULT = 1;

    /** 充满屏幕 */
    private final static int SCREEN_FULL = 0;

    private final static int SCREEN_MINI = 2;

    private CustomVideoView vv_video;

    /** 快进快退显示 */
    private TextView infoTv;

    /** 标题栏 */
    private View mOverlayHeader;
    /** 底部操作栏 */
    private View mOverlay;
    /**上一个下一个操作窗口*/
//    private LinearLayout optionOverlay;

    private TextView titleTv;


    private TextView timeTv;

    private TextView lengthTv;

    private SeekBar seekbar;

    // private Button preVideoBt;
    // private Button nextVideoBt;
    /**底边栏播放按钮*/
    private ImageView playVideoIv;

    private static final int OVERLAY_TIMEOUT = 3000;

    private static final int FADE_OUT = 1;

    private static final int SHOW_PROGRESS = 2;

    private static final int SURFACE_SIZE = 3;

    private static final int FADE_OUT_INFO = 4;

    private static final int PAUSE = 5;

    private float mTouchY;

    private float mTouchX;

    private boolean mIsAudioChanged;

    private View volumeLayout;

    private ImageView volumeSilence;

    private ImageView volumePercent;

    /** 当前声音 */
    private int currentVolume = -1;

    /** 最大声音 */
    private int maxVolume;

    private int mAudioDisplayRange;

    private AudioManager mAudioManager;

//    private View playIv;


    /** 是否在线播放或第三方应用发起播放 */
    private boolean isOnline = false;

    /** 具体的数据的路径或网络地址 */
    private Uri uri;

    /** 播放列表位置 */
    private int positionInVideoList;
    /** 视频播放位置 */
    private int position = 0;
    /**视频列表*/
    private ArrayList<VideoBaseInfo> playList;
    /**是否显示上一个下一个操作窗口*/
    private boolean isShowOptionOverlay;
    boolean overlayShowing;

    private LinearLayout waitingLl;

//    private TextView loadRateView;
    private int loadRate=-1;   //当前加载百分比

    /** 是否自动播放 */
    private boolean isAutoPlay;
    private boolean isPause = false;

    private int duration = 0;
    
    // 锁屏广播
    private LockScreenReceiver lockScreenReceiver;
    private boolean lockflag = false;
    
    private ImageView iv_result;
    private RelativeLayout layout_overback = null;
    
    /**
     * Handle resize of the surface and the overlay
     */
    private Handler mHandler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case FADE_OUT:
                    hideOverlay(false);
                    break;
                case SHOW_PROGRESS:
                    
                    int currentPosition = vv_video.getCurrentPosition();
                    if (position == currentPosition ) {  
//                        if(!playIv.isShown())
                            waitingLl.setVisibility(View.VISIBLE);  
                    } else {  
                        waitingLl.setVisibility(View.GONE);  
                        playVideoIv.setVisibility(View.VISIBLE);
                    }  
                    if(currentPosition != 0){
                        position = currentPosition;
                        waitingLl.setVisibility(View.GONE);  
                        }  
//                    Logger.i("position", "player播放进度="+position+",,百分比="+(float)position/(float)duration);
                    
                 // 更新播放进度
                    Logger.i(TAG, "currentPosition=="+currentPosition);
                    if(currentPosition == 0){
                    	if(position != 0){
                    		seekbar.setProgress(position);
                    	}else{
                    		seekbar.setProgress(0);
                    	}
                    }else{
                    	seekbar.setProgress(position);
                    }
//                    seekbar.setProgress(position);
                    if (isOnline) {

                        int j = vv_video.getBufferPercentage();
//                        Logger.i("position", "缓冲进度="+j);

                        int secondaryProgress = (j * seekbar.getMax() / 100);
                        // 更新缓冲了多少，通常播放网络资源时候用到
                        seekbar.setSecondaryProgress(secondaryProgress);
                    } else {
                        // 这里我们不需要第2进度，所以为0
                        seekbar.setSecondaryProgress(0);
                    }

                    timeTv.setText(Utils.millisToString(position));

                    sendEmptyMessageDelayed(SHOW_PROGRESS, 500);
                    break;
                case SURFACE_SIZE:
                    break;
                case FADE_OUT_INFO:
                    if (infoTv.getVisibility() == View.VISIBLE)
                        infoTv.startAnimation(AnimationUtils.loadAnimation(
                                VideoPlayerActivity.this, android.R.anim.fade_out));
                    infoTv.setVisibility(View.INVISIBLE);
                    break;
                case PAUSE:
                    break;
            }
        }
    };

    /** 声音layout定时隐藏 */
    private Handler mDismissHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            volumeLayout.setVisibility(View.GONE);
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        setContentView(R.layout.activity_video_player);
    }

    @Override
    protected void initView() {

        vv_video = (CustomVideoView) findViewById(R.id.vv);
        infoTv = (TextView) findViewById(R.id.player_overlay_info);
        /** initialize Views an their Events */
        mOverlayHeader = (View) findViewById(R.id.player_overlay_header);
        titleTv = (TextView) findViewById(R.id.player_overlay_title);
        // miniBt = (Button) findViewById(R.id.player_overlay_mini);
        // backBt = (Button) findViewById(R.id.player_overlay_back);

        mOverlay = (View) findViewById(R.id.player_overlay);
        timeTv = (TextView) findViewById(R.id.player_overlay_time);
        lengthTv = (TextView) findViewById(R.id.player_overlay_length);
        seekbar = (SeekBar) findViewById(R.id.player_overlay_seekbar);
        // preVideoBt = (Button) findViewById(R.id.player_overlay_media_rew);
        // nextVideoBt = (Button) findViewById(R.id.player_overlay_media_ff);
        playVideoIv = (ImageView) findViewById(R.id.player_overlay_media_play);
        volumeLayout = findViewById(R.id.operation_volume_brightness);
        fullVolHeight = findViewById(R.id.iv_progress_bottom).getLayoutParams().height;
        volumePercent = (ImageView) findViewById(R.id.iv_progress_top);

        volumeSilence = (ImageView) findViewById(R.id.player_overlay_silence);
//        playIv = findViewById(R.id.player_overlay_play);

        waitingLl = (LinearLayout) findViewById(R.id.waiting_ll);
        // pb = (ProgressBar) findViewById(R.id.probar);
//        loadRateView = (TextView) findViewById(R.id.load_rate);

//        optionOverlay = (LinearLayout) findViewById(R.id.ll_option_overlay);
        
        iv_result = (ImageView)findViewById(R.id.iv_result);
        layout_overback = (RelativeLayout)findViewById(R.id.player_overlay_back);
        
    }

    @Override
    protected void initData() {
      //锁屏时
        IntentFilter lockScreenFilter = new IntentFilter();
        lockScreenFilter.addAction(Intent.ACTION_SCREEN_OFF);
        lockScreenReceiver = new LockScreenReceiver();
        registerReceiver(lockScreenReceiver, lockScreenFilter);
        
//        获取屏幕尺寸
        getScreenSize();
        //获取是否自动播放
        isAutoPlay = OptionInfo.getInstance(VideoPlayerActivity.this).isVideoDetailPageAutoPlay();
        boolean isCanPlay = getIntent().getBooleanExtra("isPause", false);
        if(isCanPlay){
        	isAutoPlay = false;
        }
//        初始化声音控件
        mAudioManager = (AudioManager) getSystemService(AUDIO_SERVICE);
        maxVolume = mAudioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);

        // 得到播放列表位置
        positionInVideoList = getIntent().getIntExtra("positionInVideoList", 0);
        // 得到视频播放位置
        position = getIntent().getIntExtra("position", 0);
        Logger.i(TAG, "得到的position="+position);
        // 得到播放列表
        playList = (ArrayList<VideoBaseInfo>) getIntent().getSerializableExtra("videoList");
        //  是否显示操作按钮overlay
        isShowOptionOverlay = getIntent().getBooleanExtra("showOption", false);
        
        //
//        if(isShowOptionOverlay){
//            optionOverlay.setVisibility(View.VISIBLE);
//            MobclickAgent.onEvent(this, "zeroFlowPlay_id");
//        }else{
//            optionOverlay.setVisibility(View.GONE);
//        }
        int duration = getIntent().getIntExtra("videoDuration", 0);
        if(duration > 0){
        	if(seekbar != null){
        		seekbar.setMax(duration);
        		seekbar.setProgress(position);
        	}
        }
        if (playList != null && !playList.isEmpty() && positionInVideoList<= playList.size()) {
            // 设置播放视频源的路径
            setVideoPath(playList.get(positionInVideoList).getVideo());
            titleTv.setText(playList.get(positionInVideoList).getTitle());
        } else {
            ToastAlone.showToast(VideoPlayerActivity.this, R.string.no_play_video_msg, 1);
            back();
        }
    }


    @Override
    protected void setListener() {

        // preVideoBt.setOnClickListener(this);
        // nextVideoBt.setOnClickListener(this);
        playVideoIv.setOnClickListener(this);

        volumeSilence.setOnClickListener(this);
//        playIv.setOnClickListener(this);

        findViewById(R.id.player_overlay_zoon_in).setOnClickListener(this);
        iv_result.setOnClickListener(this);
        
        // 1,SeekBar
        // 2,播放前关联
        // 3，拖动监听
        seekbar.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {

            // 当拖动发生改变的时候执行
            @Override
            public void onProgressChanged(SeekBar seekbar, int progress, boolean fromUser) {

                if (fromUser) {
                    vv_video.seekTo(progress);
                    timeTv.setText(millisToString(progress));
                }
            }

            // 当拖动刚触动的时候执行
            @Override
            public void onStartTrackingTouch(SeekBar arg0) {
                mHandler.removeMessages(FADE_OUT);
            }

            // 当拖动刚触动的时候执行
            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                mHandler.sendEmptyMessageDelayed(FADE_OUT, OVERLAY_TIMEOUT);
            }
        });

        setListenerForVideoview();
    }

    /**
     * VideoView的初始化，设置监听
     */

    private void setListenerForVideoview() {
        vv_video.setOnSeekCompleteListener(new OnSeekCompleteListener() {

            @Override
            public void onSeekComplete(MediaPlayer mp) {
            }
        });

        /**
         * 监听播放出错时的处理
         */
        vv_video.setOnErrorListener(new OnErrorListener() {

            @Override
            public boolean onError(MediaPlayer mp, int what, int extra) {
//                Log.i("onerror", "what="+what+",extra="+extra);
                if (vv_video != null) {
                    vv_video.stopPlayback();
                    switch (extra) {//extra的错误码很奇怪，没有匹配的，基本上都走default
                        case  MediaPlayer.MEDIA_ERROR_IO:
                            ToastAlone.showToast(VideoPlayerActivity.this, "视频源或网络错误", 1);
                            break;
                        case  MediaPlayer.MEDIA_ERROR_MALFORMED:
                            ToastAlone.showToast(VideoPlayerActivity.this, "视频编码或文件错误", 1);
                            break;
                        case  MediaPlayer.MEDIA_ERROR_UNSUPPORTED:
                            ToastAlone.showToast(VideoPlayerActivity.this, "视频格式不支持", 1);
                            break;
                        case  MediaPlayer.MEDIA_ERROR_TIMED_OUT:
                            if (playList != null && !playList.isEmpty() && positionInVideoList<= playList.size()) {
                                // 设置播放视频源的路径
                                setVideoPath(playList.get(positionInVideoList).getVideo());
                                titleTv.setText(playList.get(positionInVideoList).getTitle());
                                ToastAlone.showToast(VideoPlayerActivity.this, "视频播放出错，正在重新请求", 1);
                            } 
                            break;
                        default :
                            ToastAlone.showToast(VideoPlayerActivity.this, "视频播放未知错误", 1);
                            break;
                    }
                }
                return true;
            }
        });

        vv_video.setSizeChangeLinstener(new SizeChangeLinstener() {

            @Override
            public void doMyThings() {
                setVideoScale(SCREEN_DEFAULT);
            }
        });

        vv_video.setOnPreparedListener(new OnPreparedListener() {

            @Override
            public void onPrepared(MediaPlayer arg0) {

                if (!overlayShowing) {
                    showOverlay();
                }
                Logger.i(TAG, "vv_video.setOnPreparedListener了了了了了子");
                setVideoScale(SCREEN_DEFAULT);

                int i = vv_video.getDuration();
                duration = i;
                
                Logger.d(TAG, "duration=" + i);
                // 视频文件和seekBar关联：视频有多长那么seekBar拖动也在这个范围内
                seekbar.setMax(i);
                vv_video.seekTo(position);
                if(position == 0){
                	vv_video.seekTo(1);//ft_8.29笨方法
                }                
                timeTv.setText(Utils.millisToString(position));
                lengthTv.setText(Utils.millisToString(i));

                if(isAutoPlay){
                    videoStart();
                }else{
                    videoPause();
                }
            }
        });

        vv_video.setOnCompletionListener(new OnCompletionListener() {

            @Override
            public void onCompletion(MediaPlayer arg0) {
                position = 0;
                int n = playList.size();
                if (++positionInVideoList < n) {
                    setVideoPath(playList.get(positionInVideoList).getVideo());
                    titleTv.setText(playList.get(positionInVideoList).getTitle());
                    if(isAutoPlay){
                        videoStart();
                    }else{
                        videoPause();
                    }
                } else {
//                    Toast.makeText(VideoPlayerActivity.this, R.string.last_video_msg, 0).show();
//                    --positionInVideoList;
//                    vv_video.seekTo(position);
//                    seekbar.setProgress(position);
//                    timeTv.setText(String.format("%02d:%02d", 0, 0));
//                    
//                    playVideoIv.setImageResource(R.drawable.icon_play_mini);
//                    playIv.setVisibility(View.VISIBLE);
//                    mHandler.removeMessages(SHOW_PROGRESS);
                	isAutoPlay = false;
                    back();
                }
            }
        });

        vv_video.setOnBufferingUpdateListener(new OnBufferingUpdateListener() {

            @Override
            public void onBufferingUpdate(MediaPlayer mp, int percent) {
//                loadRateView.setText(percent + "%");
                loadRate = percent;
            }
        });
    }


    
    /**
     * 暂停。继续播放使用
     */
    private void updatePausePlay() {
        if (vv_video.isPlaying()) {
            videoPause();
        } else {
            videoStart();
        }
    }
    
    private void videoStart() {
        vv_video.start();
        isPause = false;
        updateVideoPalyerUI(true);
    }
    
    private void videoPause(){
        vv_video.pause();
        isPause = true;
        updateVideoPalyerUI(false);
    }
    
    /**
     * 修改播放器ui
     * @param isPlay    是否正在播放，true播放，false未播放
     */
    private void updateVideoPalyerUI(boolean isPlay) {
        mHandler.removeMessages(SHOW_PROGRESS);
        if(isPlay){
//            playVideoIv.setImageResource(R.drawable.ic_media_pause);
        	playVideoIv.setImageResource(R.drawable.btn_play_video_pause);
        	
//            playIv.setVisibility(View.GONE);
            mHandler.sendEmptyMessage(SHOW_PROGRESS);
        }else{
            waitingLl.setVisibility(View.GONE);
//            playVideoIv.setImageResource(R.drawable.icon_play_mini);
            playVideoIv.setImageResource(R.drawable.btn_play_video);
//            playIv.setVisibility(View.VISIBLE);
        }
    }

    /**
     * 设置视频播放屏幕大小的模式
     * 
     * @param flag
     */
    private void setVideoScale(int flag) {

        switch (flag) {
            case SCREEN_FULL:

            	Logger.d("ControllerActivity", "screenWidth: " + screenWidth + " screenHeight: "
                        + screenHeight);
                vv_video.setVideoScale(screenWidth, screenHeight);

                break;

            case SCREEN_DEFAULT:

                int videoWidth = vv_video.getVideoWidth();
                int videoHeight = vv_video.getVideoHeight();
                int mWidth = screenWidth;
                int mHeight = screenHeight;

                if (videoWidth > 0 && videoHeight > 0) {
                    if (videoWidth * mHeight > mWidth * videoHeight) {

                        mHeight = mWidth * videoHeight / videoWidth;
                    } else if (videoWidth * mHeight < mWidth * videoHeight) {

                        mWidth = mHeight * videoWidth / videoHeight;
                    } else {

                    }
                }

                vv_video.setVideoScale(mWidth, mHeight);
                break;
        }
    }

    /**
     * 获得手机或模拟器屏蔽高和宽，并计算好控制面板的高度
     */
    private void getScreenSize() {
        Display display = getWindowManager().getDefaultDisplay();
        screenHeight = display.getHeight();
        screenWidth = display.getWidth();
        Logger.i(TAG, "screenHeight="+screenHeight+"__screenWidth="+screenWidth);
    }

    /**
     * show overlay the the default timeout
     */
    private void showOverlay() {
        showOverlay(OVERLAY_TIMEOUT);
    }

    /**
     * show overlay
     */
    private void showOverlay(int timeout) {
        mHandler.sendEmptyMessage(SHOW_PROGRESS);
        if (!overlayShowing) {
            overlayShowing = true;
//            mOverlayHeader.setVisibility(View.VISIBLE);
//            mOverlay.setVisibility(View.VISIBLE);
////            if(isShowOptionOverlay){
////                optionOverlay.setVisibility(View.VISIBLE);
////            }else{
////                optionOverlay.setVisibility(View.GONE);
////            }
            layout_overback.setVisibility(View.VISIBLE);
        }
        Message msg = mHandler.obtainMessage(FADE_OUT);
        if (timeout != 0) {
            mHandler.removeMessages(FADE_OUT);
            mHandler.sendMessageDelayed(msg, timeout);
        }
    }
    
    /**
	 * show overlay
	 */
	private void showOverlayNo() {
		if (!overlayShowing) {
			overlayShowing = true;
			layout_overback.setVisibility(View.VISIBLE);
		}
	}


    /**
     * hider overlay
     */
    private void hideOverlay(boolean fromUser) {
        if (overlayShowing) {
//            mHandler.removeMessages(SHOW_PROGRESS);
//            if (!fromUser) {
//                mOverlayHeader.startAnimation(AnimationUtils.loadAnimation(this,android.R.anim.fade_out));
//                mOverlay.startAnimation(AnimationUtils.loadAnimation(this, android.R.anim.fade_out));
////                if(isShowOptionOverlay){
////                    optionOverlay.startAnimation(AnimationUtils.loadAnimation(this, android.R.anim.fade_out));
////                }
//            }
//            mOverlayHeader.setVisibility(View.INVISIBLE);
//            mOverlay.setVisibility(View.INVISIBLE);
////            if(isShowOptionOverlay){
////                optionOverlay.setVisibility(View.INVISIBLE);
////            }else{
////                optionOverlay.setVisibility(View.GONE);
////            }
            layout_overback.setVisibility(View.GONE);
            overlayShowing = false;
        }
    }

    /**
     * hide the info view with "delay" milliseconds delay
     * 
     * @param delay
     */
    private void hideInfo(int delay) {
        mHandler.sendEmptyMessageDelayed(FADE_OUT_INFO, delay);
    }

    /**
     * hide the info view
     */
    private void hideInfo() {
        hideInfo(0);
    }

    /** 手势结束 */
    private void endGesture() {
        currentVolume = -1;

        // 隐藏
        mDismissHandler.removeMessages(0);
        mDismissHandler.sendEmptyMessageDelayed(0, 1000);
    }

    private int WHEEL_DEAD_ZONE = 7;

    private int mSeekTo = -1;

    @Override
    public boolean onTouchEvent(MotionEvent event) {

        switch (event.getAction()) {

            case MotionEvent.ACTION_DOWN:
                mTouchY = event.getRawY();
                mTouchX = event.getRawX();
                currentVolume = mAudioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
                mIsAudioChanged = false;
                break;

            case MotionEvent.ACTION_MOVE:
                float y = event.getRawY();
                float x = event.getRawX();
                if (Math.abs(y - mTouchY) > 50 || Math.abs(x - mTouchX) > 50) {
                    if (Math.abs(y - mTouchY) > 50) {
                        onVolumeSlide((mTouchY - y) / screenHeight);
                    } else if (Math.abs(x - mTouchX) > 50) {

                        int delta = (int) (x - mTouchX);
                        if (vv_video != null && Math.abs(delta) >= WHEEL_DEAD_ZONE) {
                            delta -= Math.signum(delta) * WHEEL_DEAD_ZONE;

                            mSeekTo = Math.max(0, vv_video.getCurrentPosition() + delta * 100);
                            mSeekTo = Math.min(vv_video.getDuration(),
                                    vv_video.getCurrentPosition() + delta * 100);
                        } else
                            delta = 0;
                        if (mSeekTo >= 0)
                            showInfo(millisToString(mSeekTo));

                    }

                    mIsAudioChanged = true;
                }
                break;

            case MotionEvent.ACTION_UP:
                if (!mIsAudioChanged) {
                    if (!overlayShowing) {
                        showOverlay();
//                    	showOverlayNo();
                    } else {
                        hideOverlay(true);
                    }
                } else {
                    endGesture();
                    if(vv_video != null && vv_video.isPlaying() && mSeekTo != -1){//只有播放的时候才操作这些东西
                        if (mSeekTo < 0) {
                            // showInfo("00:00");
                            mSeekTo = 0;
                        } 
                        vv_video.seekTo(mSeekTo);
                        timeTv.setText(millisToString(mSeekTo));
                        mSeekTo = -1;
                    }
                    hideInfo();

                }

                break;
        }
        return mIsAudioChanged;
    }

    /**
     * Show text in the info view for "duration" milliseconds
     * 
     * @param text
     * @param duration
     */
    private void showInfo(String text, int duration) {
        infoTv.setVisibility(View.VISIBLE);
        infoTv.setText(text);
        mHandler.removeMessages(FADE_OUT_INFO);
        mHandler.sendEmptyMessageDelayed(FADE_OUT_INFO, duration);
    }

    private void showInfo(int textid, int duration) {
        infoTv.setVisibility(View.VISIBLE);
        infoTv.setText(textid);
        mHandler.removeMessages(FADE_OUT_INFO);
        mHandler.sendEmptyMessageDelayed(FADE_OUT_INFO, duration);
    }

    /**
     * Show text in the info view
     * 
     * @param text
     */
    private void showInfo(String text) {
        infoTv.setVisibility(View.VISIBLE);
        infoTv.setText(text);
        mHandler.removeMessages(FADE_OUT_INFO);
    }

    /**
     * 滑动改变声音大小
     * 
     * @param percent
     */
    private void onVolumeSlide(float percent) {
        // int delta = (int) (((mTouchY - y) / mAudioDisplayRange) * mAudioMax);
        // int vol = (int) Math.min(Math.max(mVol + delta, 0), mAudioMax);
        // if (delta != 0) {
        // mAudioManager.setStreamVolume(AudioManager.STREAM_MUSIC, vol,
        // AudioManager.FLAG_SHOW_UI);
        // }
        // if (currentVolume == -1) {
        // currentVolume =
        // mAudioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
        if (currentVolume < 0)
            currentVolume = 0;

        // 显示
        volumeLayout.setVisibility(View.VISIBLE);
        // }

        int index = (int) (percent * maxVolume) + currentVolume;
        if (index > maxVolume)
            index = maxVolume;
        else if (index < 0)
            index = 0;

        // 变更声音
        changeVol(index);
    }

    private void changeVol(int index) {
        if (index == 0) {
            // ic_lock_silent_mode
            volumeSilence.setBackgroundResource(R.drawable.ic_lock_silent_mode);
        } else {
            volumeSilence.setBackgroundResource(R.drawable.ic_lock_silent_mode_off);
        }
        mAudioManager.setStreamVolume(AudioManager.STREAM_MUSIC, index, 0);
        ViewGroup.LayoutParams lp = volumePercent.getLayoutParams();
        lp.height = fullVolHeight * index / maxVolume;
        volumePercent.setLayoutParams(lp);
    }
    
    @Override
    protected void onResume() {
        super.onResume();
        videoStart();
    }

    @Override
    protected void onPause() {
        super.onPause();
        mHandler.sendEmptyMessage(PAUSE);
        videoPause();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        mAudioManager = null;
        mHandler.removeMessages(SHOW_PROGRESS);
        mHandler.removeMessages(FADE_OUT);
//        if (vv_video.isPlaying()) {
//            vv_video.stopPlayback();
//        }
        if (playList != null) {
            playList.clear();
        }
        
        unregisterReceiver(lockScreenReceiver);
        lockScreenReceiver = null;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.player_overlay_silence:
                changeVol(0);
                // volSeekBar.setProgress(0);
                //
                // mAudioManager.setStreamVolume(AudioManager.STREAM_MUSIC, 0,
                // 0);
                break;
//             case R.id.option_overlay_media_pre:
//                 playPre();
//             break;
//             case R.id.option_overlay_media_next:
//                 playNext();
//             break;
//             case R.id.option_overlay_home:
//                 backToHome();
//                 break;
            case R.id.player_overlay_media_play:
                updatePausePlay();
                break;
            case R.id.iv_result:
            case R.id.player_overlay_zoon_in:
                back();
                break;
//            case R.id.player_overlay_play:
//                updatePausePlay();
//                break;
        }

    }

    
    
    @Override
	public void onBackPressed() {
		// TODO Auto-generated method stub
//		super.onBackPressed();
		back();
	}

	/**
     * 关闭,返回来源页面
     */
    private void back() {
        if(lockflag){
            lockflag = false;
        }else{
        	Logger.i(TAG, "下面执行setResult");
            setResult(RESULT_OK, new Intent().putExtra("position", vv_video.getCurrentPosition()).putExtra("isPause", isPause));
            finish();
        }
    }    
    
    /**
     * 关闭去home页面
     */
    private void backToHome() {
        startActivity(new Intent(VideoPlayerActivity.this,MainPageNewActivity.class));
        finish();
    }

    private void playPre() {

        long time = System.currentTimeMillis();

        if (time - lastTimem < CLICK_INTERVAL) {
            return;
        }
        lastTimem = time;
        int n = playList.size();
        if (--positionInVideoList >= 0 && positionInVideoList < n) {
            position = 0;
            setVideoPath(playList.get(positionInVideoList).getVideo());
            titleTv.setText(playList.get(positionInVideoList).getTitle());
            mHandler.removeMessages(FADE_OUT);
            mHandler.sendEmptyMessageDelayed(FADE_OUT, OVERLAY_TIMEOUT);

        } else {
            //当前已经是第一个
            positionInVideoList = 0;
            ToastAlone.showToast(VideoPlayerActivity.this, R.string.front_video_msg, 0);

        }

    }

    private static long CLICK_INTERVAL = 800;

    long lastTimem;

    private int fullVolHeight;

    private void playNext() {

        // 防止频繁点击
        long time = System.currentTimeMillis();
        if (time - lastTimem < CLICK_INTERVAL) {
            return;
        }
        lastTimem = time;

        if (playList == null)
            return;

        if (playList != null) {
            int n = playList.size();
            if (++positionInVideoList < n && positionInVideoList >= 0) {
                position = 0;
                String playUri = playList.get(positionInVideoList).getVideo();
                setVideoPath(playUri);
                titleTv.setText(playList.get(positionInVideoList).getTitle());
                mHandler.removeMessages(FADE_OUT);
                mHandler.sendEmptyMessageDelayed(FADE_OUT, OVERLAY_TIMEOUT);

            } else {
                //
                ToastAlone.showToast(VideoPlayerActivity.this, R.string.last_video_msg, 0);
                if (positionInVideoList > 0) {
                    --positionInVideoList;
                }
            }
        }

    }

    private void setVideoPath(String path) {
        if (path.startsWith("http:")) {
            isOnline = true;
//            vv_video.setVideoURI(Uri.parse(path));
            vv_video.setVideoURI(Uri.parse(path));
            overlayShowing = true;
            hideOverlay(true);
        } else {
            isOnline = false;
            vv_video.setVideoPath(path);
        }
    }

    private String millisToString(int i) {
        i /= 1000;
        int minute = i / 60;
        int hour = minute / 60;
        int second = i % 60;
        minute %= 60;
        if (hour > 0) {
            return String.format("%02d:%02d:%02d", hour, minute, second);
        } else {
            return String.format("%02d:%02d", minute, second);
        }
    }

    // ///////////////////////////测试使用

    public void takepic(View v) {
        // MediaMetadataRetriever rev = new MediaMetadataRetriever();
        // rev.setDataSource(this, TempV1.VIDEO_PATH);
        // //这里第一个参数需要Context，传this指针
        // Bitmap bitmap = rev.getFrameAtTime(vv_video.getCurrentPosition() *
        // 1000,MediaMetadataRetriever.OPTION_CLOSEST_SYNC);
        new Thread() {
            public void run() {
                videoFrame(playList.get(positionInVideoList).getVideo(), (long) vv_video.getCurrentPosition());
            }
        }.start();

    }

    public Bitmap videoFrame(String uri, long msec) {
        MediaMetadataRetriever retriever = new MediaMetadataRetriever();
        Bitmap bitmap = null;
        try {
            retriever.setDataSource(uri);
            bitmap = retriever.getFrameAtTime(msec,MediaMetadataRetriever.OPTION_CLOSEST_SYNC);
        } catch (IllegalArgumentException ex) {
            ex.printStackTrace();
        } catch (RuntimeException ex) {
            ex.printStackTrace();
        } finally {
            try {
                retriever.release();
            } catch (RuntimeException ex) {
            }
        }
        String path = Environment.getExternalStorageDirectory() + File.separator
                + System.currentTimeMillis() + ".jpg";
        try {
            FileOutputStream fos = new FileOutputStream(path);
            bitmap.compress(CompressFormat.JPEG, 80, fos);
            fos.flush();
            fos.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return bitmap;
    }

    private static Bitmap takeScreenShotVideo(int videoPosition,String videoSource) {  
        Bitmap bitmap = null;  
        android.media.MediaMetadataRetriever retriever = new android.media.MediaMetadataRetriever();  
        try {
            retriever.setDataSource(videoSource);  
            bitmap = retriever.getFrameAtTime(videoPosition*1000,MediaMetadataRetriever.OPTION_CLOSEST_SYNC);  //us
        } catch (IllegalArgumentException ex) {   
        } catch (RuntimeException ex) {  
        } finally {  
            try {  
                retriever.release();  
            } catch (RuntimeException ex) {  
                // Ignore failures while cleaning up.  
                ex.printStackTrace();
            }  
        }  
        return bitmap;  
    }  
    

    /**
     * 锁屏广播接收者
     */
    private class LockScreenReceiver extends BroadcastReceiver{

        @Override
        public void onReceive(Context context, Intent intent) {
            lockflag = true;
            Logger.i(TAG, "锁屏了");
        }
    }
}
